package j05suo;

public class J1 {
    //火车票
    static int count = 100;
    //任意对象，都可以当做锁
    static Object lock = new Object();
    //
//    J1.class

    public static void main(String[] args) {
        System.out.println(J1.class);
        Thread t1 = new Thread(()->{
            //count = 1
            while (count>0){
                //代码随时可能暂停
                //不要同时去卖
                //count = 0
                synchronized (lock){
                    if(count==0){
                        break;
                    }
                    System.out.println("t1卖票,count="+count);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    count--;
                }

            }
        });
        Thread t2 = new Thread(()->{
            while (count>0){
                //lock被锁，会等待...
                synchronized (lock){
                    if(count==0){
                        break;
                    }
                    System.out.println("t2卖票,count="+count);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    count--;
                }
            }
        });
        t1.start();
        t2.start();
    }
}

class R1 implements Runnable{
    int count = 100;
    @Override
    public void run() {
        while (count>0){
            //10
            sell();
        }
    }
    //R1.class ，静态
    //this 非静态
    public synchronized void sell(){
        System.out.println(Thread.currentThread().getName()+"卖票，count="+count);
        count--;
    }
}
class J2{
    public static void main(String[] args) {
        R1 r = new R1();
        Thread t1 = new Thread(r,"t1111");
        Thread t2 = new Thread(r,"t2222");

        t1.start();
        t2.start();
    }
}
